package com.sense.lib.webview.utils;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;

import androidx.core.content.FileProvider;

import java.io.File;
import java.util.List;

/**
 * <br> ClassName:   FileProvider
 * <br> Description: 提供文件访问权限授予等方法
 * <br>
 * <br> Author:      lionszhang
 * <br> Date:        2017/9/18 9:59
 */
public class FileProviderUtil {


    /**
     * <br> Description: 获取查看文件ntent
     * <br> Author:      lionszhang
     * <br> Date:        2017/9/18 10:26
     *
     * @param context 上下文
     * @param path    安装文件路径
     * @return 安装Intent
     */
    public static Intent getScanFileIntent(Context context, String path, String mimeType) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File file = new File(path);
        try {
            setIntentDataAndType(context, intent,
                    mimeType
                    , file, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return intent;
    }

    /**
     * <br> Description: 获取安装Intent
     * <br> Author:      lionszhang
     * <br> Date:        2017/9/18 10:26
     *
     * @param context 上下文
     * @param file    安装文件
     * @return 安装Intent
     */
    public static Intent getInstallApkIntent(Context context, File file) {
        Intent installAPKIntent = new Intent(Intent.ACTION_VIEW);
        setIntentDataAndType(context, installAPKIntent,
                "application/vnd.android.package-archive"
                , file, false);
        installAPKIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return installAPKIntent;
    }

    /**
     * <br> Description: 获取访问文件Uri
     * <br> Author:      lionszhang
     * <br> Date:        2017/9/18 10:00
     *
     * @param context 上下文
     * @param file    文件
     * @return
     */
    public static Uri getUriForFile(Context context, File file) {
        Uri fileUri = null;
        if (Build.VERSION.SDK_INT >= 24) {
            fileUri = getUriForFile24(context, file);
        } else {
            fileUri = Uri.fromFile(file);
        }
        return fileUri;
    }

    /**
     * <br> Description: 获取api>=24的访问文件Uri
     * <br> Author:      lionszhang
     * <br> Date:        2017/9/18 10:02
     *
     * @param context 上下文
     * @param file    文件
     * @return
     */
    public static Uri getUriForFile24(Context context, File file) {
        Uri fileUri = FileProvider.getUriForFile(context,
                context.getPackageName() + ".provider",
                file);
        return fileUri;
    }

    /**
     * <br> Description: 获取封装的IntentData
     * <br> Author:      lionszhang
     * <br> Date:        2017/9/18 10:03
     *
     * @param context   上下文
     * @param intent    跳转的Intent
     * @param type      需要添加的Intent标志
     * @param file      文件
     * @param writeAble 是否需要写入操作权限
     */
    public static void setIntentDataAndType(Context context,
                                            Intent intent,
                                            String type,
                                            File file,
                                            boolean writeAble) {
        if (Build.VERSION.SDK_INT >= 24) {
            intent.setDataAndType(getUriForFile(context, file), type);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            if (writeAble) {
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }
        } else {
            intent.setDataAndType(Uri.fromFile(file), type);
        }
    }

    /**
     * <br> Description: 获取封装的IntnetData
     * <br> Author:      lionszhang
     * <br> Date:        2017/9/18 10:04
     *
     * @param context   上下文
     * @param intent    intent
     * @param file      文件
     * @param writeAble 是否需要写入操作权限
     */
    public static void setIntentData(Context context,
                                     Intent intent,
                                     File file,
                                     boolean writeAble) {
        if (Build.VERSION.SDK_INT >= 24) {
            intent.setData(getUriForFile(context, file));
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            if (writeAble) {
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }
        } else {
            intent.setData(Uri.fromFile(file));
        }
    }


    /**
     * <br> Description: uri读写授权
     * <br> Author:      lionszhang
     * <br> Date:        2017/9/18 10:05
     *
     * @param context   上下文
     * @param intent    跳转intent
     * @param uri       文件Uri
     * @param writeAble 是否需要写入操作
     */
    public static void grantPermissions(Context context, Intent intent, Uri uri, boolean writeAble) {

        int flag = Intent.FLAG_GRANT_READ_URI_PERMISSION;
        if (writeAble) {
            flag |= Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
        }
        intent.addFlags(flag);
        List<ResolveInfo> resInfoList = context.getPackageManager()
                .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo resolveInfo : resInfoList) {
            String packageName = resolveInfo.activityInfo.packageName;
            context.grantUriPermission(packageName, uri, flag);
        }
    }


    /**
     * 获取uri
     *
     * @param context
     * @param file
     * @return
     */
    public static Uri getUriForFile2(Context context, File file) {
        Uri fileUri = null;
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                ContentValues contentValues = new ContentValues();
                contentValues.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
                contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, file.getName());
                contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                fileUri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                fileUri = getUriForFile24(context, file);
            } else {
                fileUri = Uri.fromFile(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileUri;
    }


    /**
     * <br> Description: uri读写授权
     * <br> Author:      lionszhang
     * <br> Date:        2017/9/18 10:05
     *
     * @param context 上下文
     * @param file    pai zhao baocun de wen jian lu jing
     */
    public static Intent getTakePictureIntent(Context context, File file) {
        Uri outputUri;
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        //存放拍照的图片文件
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            outputUri = getUriForFile24(context, file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            outputUri= Uri.fromFile(file);
        }
//        Uri outputUri = getUriForFile2(context, file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);

        return intent;
    }

    /**
     * <br> Description: uri读写授权
     * <br> Author:      lionszhang
     * <br> Date:        2017/9/18 10:05
     *
     * @param context 上下文
     * @param file    pai zhao baocun de wen jian lu jing
     */
    public static Intent getCropPictureIntent(Context context, File file) {



//        Uri  outputUri = Uri.parse("file://" +"/" + Constants.FILE_HEAD_PATH_CROP);//裁剪输出文件
//        Uri outputUri = Uri.fromFile(WebFileUtil.INSTANCE.getFileByName(context, "IMG_CROP_OUT.jpg"));//裁剪输出文件
        Uri outputUri = getUriForFile2(context, WebFileUtil.INSTANCE.getFileByName(context, "IMG_CROP_OUT.jpg"));
        Intent intent = new Intent("com.android.camera.action.CROP");
        Uri imageUri= getUriForFile2(context, file);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(imageUri, "image/*");
        intent.putExtra("crop", "true");

        //设置宽高比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(WebFileUtil.INSTANCE.getFileByName(context, "IMG_CROP_OUT.jpg")));
        }
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        return intent;
    }


    /**
     * <br> Description: uri读写授权
     * <br> Author:     lionszhang
     * <br> Date:        2017/9/18 10:05
     *
     * @param uri xiangche baocun de wen jian lu jing
     */
    public static Intent getCropPictureIntent(Context context, Uri uri) {

//        Uri  outputUri = Uri.parse("file://" +"/" + Constants.FILE_HEAD_PATH_CROP);//裁剪输出文件
//        Uri outputUri = Uri.fromFile(WebFileUtil.INSTANCE.getFileByName(context, "IMG_CROP_OUT.jpg"));//裁剪输出文件
        Uri outputUri = getUriForFile2(context, WebFileUtil.INSTANCE.getFileByName(context, "IMG_CROP_OUT.jpg"));
        Intent intent = new Intent("com.android.camera.action.CROP");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }


        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");

        //设置宽高比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(WebFileUtil.INSTANCE.getFileByName(context, "IMG_CROP_OUT.jpg")));
        }
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        return intent;
    }

    /**
     * <br> Description: uri读写授权
     * <br> Author:      lionszhang
     * <br> Date:        2017/9/18 10:05
     */
    public static Intent getSelectPictureIntent() {

        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");

        return intent;

    }

    public static Intent createCamcorderIntent() {
        return new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    }

    public static Intent createSoundRecorderIntent() {
        return new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
    }

}
